// rnc
import React, {Component} from 'react';
import {ActivityIndicator, FlatList, Image, Text, View} from 'react-native';

export default class App extends Component {
  state = {data: [], refreshing: false};

  componentDidMount() {
    const url = 'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=0';

    fetch(url)
      .then(res => res.json())
      .then(res => {
        console.log(res);

        this.setState({data: res.data});
      });
  }

  render() {
    return (
      <FlatList
        data={this.state.data}
        keyExtractor={(item, index) => index + ''}
        renderItem={this._renderItem}
        ItemSeparatorComponent={() => (
          <View style={{height: 1, backgroundColor: 'gray'}} />
        )}
        ListFooterComponent={this._ListFooterComponent}
        onEndReached={this._onEndReached}
        onEndReachedThreshold={0.1}
        onRefresh={this._onRefresh}
        refreshing={this.state.refreshing}
      />
    );
  }

  _onRefresh = () => {
    this.setState({refreshing: true});

    const url = 'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=0';

    fetch(url)
      .then(res => res.json())
      .then(res => {
        console.log(res);

        this.setState({data: res.data, refreshing: false});
      });
  };

  _onEndReached = () => {
    const url =
      'http://capi.douyucdn.cn/api/v1/live?limit=20&offset=' +
      this.state.data.length;

    fetch(url)
      .then(res => res.json())
      .then(res => {
        console.log(res);

        this.setState({data: this.state.data.concat(res.data)});
      });
  };

  _ListFooterComponent = () => (
    <View style={{alignItems: 'center', backgroundColor: 'lightgray'}}>
      <ActivityIndicator color="yellow" size="large" />
      <Text style={{fontSize: 22}}>加载中...</Text>
    </View>
  );

  _renderItem = ({item}) => (
    <View style={{padding: 6, flexDirection: 'row'}}>
      <Image source={{uri: item.room_src}} style={{width: 200, height: 120}} />
      <View style={{marginLeft: 6, flex: 1, justifyContent: 'space-around'}}>
        <Text style={{fontSize: 24}}>{item.room_name}</Text>
        <Text style={{fontSize: 22, color: 'orange'}}>{item.nickname}</Text>
      </View>
    </View>
  );
}
